import { createRouter, createWebHistory } from 'vue-router'

// 初始路由配置，不包含动态加载的菜单项
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'login',
      component: () => import('../views/login.vue')
    },
    {
      path: '/index',
      name: 'index',
      component: () => import('../layout/index.vue'),
      // 初始时不包含子路由
    },
    {
      path: '/404',
      name: '404',
      component: () => import('../views/404.vue')
      // 初始时不包含子路由
    },
  ]
})

import { urlStore } from '@/store/urlStore'
import { useUserStore1 } from '@/store/userStore'
import { uidStore } from '@/store/uidStore'
import { breadcrumbStore } from '@/store/breadcrumbStore'
import request from '@/request/request'
import { ElMessage } from 'element-plus'

const whiteRouter = ['/', '/login', '/error', '/404']
let load = 0

router.beforeEach((to, from, next) => {

  console.log(to);
  console.log(from);
  
  window.scrollTo(0, 0);
  const menus=breadcrumbStore()
  const user=useUserStore1()

  var boo=true
   menus.menus.forEach(element => {
    if (element!=null&&element.path==to.path) {
      boo=false
    }
  });
  if (boo&&user.userInfo.length!=0) {
    user.userInfo.menus.forEach(element => {
      element.menus.forEach(item => {
        if (item.url==to.path) {
          menus.addMenus({name:item.menuName,path:to.path})
        }
      });
    });
  }
    
    if (whiteRouter.indexOf(to.path) == -1) {
        const url=urlStore()
        if (url.urls.length == 0 || load == 0) {
          setTimeout(()=>{
            if (uidStore().uid.length!=0) {
            request({
              url: "/examination/user/getMenusUrl",
              method: "get",
              params:{
                uid:uidStore().uid
              }
            }).then(res=>{
              if (res.data.code==200) {
                const routesToAdd = res.data.obj.map(element => ({
                path: element.url,
                name: element.perms,
                text: element.url.split("/")[1],
                // 假设后端返回了正确的组件名称或路径
                component: () => import(`../views/${element.url.split("/")[1]}/${element.url.split("/")[2]}.vue`)
                // 注意：这里应该使用 element.componentPath 或类似的字段，而不是解析 URL
              }));
              url.setUrl(routesToAdd)
              const routerList = url.urls
              router.addRoute({
                  path: '/user/index',
                  name: 'index',
                  component: () => import('../layout/index.vue'),
                  children: routerList
              }) 
              }
              
              load ++
              next({ ...to, replace: true })
            });
          }else{
            ElMessage.error("用户信息过期 请重新登录")
            router.push("/")
          }
          },500)
        } else {
            if (to.matched.length != 0) {
                next()
            } else {
                next('/404')
            }
        }
    }
     else {
        next()
    }
})

export default router;
